﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Tools.Helper;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.回氦)]
    public class BackHelium : ServierBase
    {
        public BackHelium(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporary, HomeStatic homeStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporary,homeStatic)
        {

        }

        public override Task Handle(Context.DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号);
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen(plc.Communication, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_AfterWeighing, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                #region 回氦数据获取
                List<BatteryBackHeliumDataModel> batteryBackHelia = new List<BatteryBackHeliumDataModel>();
                if (context.Struct_Length < 9)
                {
                    BatteryBackHeliumDataArrayModel batteryBackHeliaModel = new BatteryBackHeliumDataArrayModel(context.Struct_Length);
                    plc.Communication.ReadClass(8200, batteryBackHeliaModel);//定死的地址
                    batteryBackHelia.AddRange(batteryBackHeliaModel.Data);
                }
                else
                {
                    for (int i = 0; i < 2; i++)
                    {
                        BatteryBackHeliumDataArrayModel batteryBackHeliaModel = new BatteryBackHeliumDataArrayModel(8);
                        plc.Communication.ReadClass(8200 + (8 * i * 26), batteryBackHeliaModel);//定死的地址
                        batteryBackHelia.AddRange(batteryBackHeliaModel.Data);
                    }
                }
                RunLog($"接收到的数据：{System.Text.Json.JsonSerializer.Serialize(batteryBackHelia, GlobalStatic.Options)}");
                #endregion
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");

            }
            catch (Exception ex)
            {
                RunLog($"异常：{ex}");
            }
            return base.Handle(context);
        }
    }
}
